<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

class Category extends AdminBackEndController {
    public function __construct() {
        parent::__construct();
        $this->load->model('repo/category_model', 'cate_model');
        $this->load->helper('file');
    }

    public function index() {
        $aCate = $this->cate_model->getCategories(array('id <>' => 0));
        $aReturn = array('pageTitle' => 'Danh mục sản phẩm', 'aCate' => $aCate);
        $this->renderView('backend/admin/category/index', $aReturn);
    }

    public function get($slug) {
        $oCate = $this->cate_model->getCateBySlug($slug, true);
        if ($oCate == null) {
            show_404();
        }
        $aReturn = array(
            'pageTitle' => $oCate->getTitle(),
            'oCate' => $oCate,
            'action' => 'update',
            'action_link' => admin_page_url(CATEGORY_SLUG . '/' . UPDATE_SLUG . '/do'));
        $this->renderView('backend/admin/category/single', $aReturn);
    }

    private function validate($category = null) {
        $this->form_validation->set_rules('category[title]', 'lang:category_title', 'trim|required|max_length[100]|xss_clean');
        $this->form_validation->set_rules('category[slug]',  'lang:category_slug',  'trim|required|callback_slug_check|xss_clean');
        $this->form_validation->set_rules('category[order]', 'lang:category_order', 'trim|required|max_length[10]|integer|xss_clean');
        $this->form_validation->set_error_delimiters('<li>', '</li>');
    }

    public function insert() {
        $aReturn = array(
            'pageTitle' => 'Thêm',
            'action' => 'insert',
            'action_link' => admin_page_url(CATEGORY_SLUG . '/' . INSERT_SLUG . '/do'),
            'oCate' => new Category_Entity());
        $this->renderView('backend/admin/category/single', $aReturn);
    }

    public function doInsert() {
        $aResult = array();
        $date = get_current_date();
        $category = $this->input->post('category', true);
        $this->validate();
        if ($this->form_validation->run() == false) {
            $aResult = array(
                'code' => 0,
                'title' => $this->lang->line('insert_fail'),
                'text' => '<ul>' . validation_errors() . '</ul>',
                );
        } else {
            //check cate slug exist
            $isCateExist = $this->cate_model->checkCategoryExists($category['slug']);
            if ($isCateExist > 0) {
                $aResult = array(
                    'code' => 0,
                    'title' => $this->lang->line('insert_fail'),
                    'text' => '<ul><li>' . $this->lang->line('category_exist') . '</li></ul>',
                    );
            } else {
                //set created_at
                $category['created_at'] = $date;
                if (isset($category['publish_flg']) && $category['publish_flg'] == 1) {
                    $category['deleted_at'] = null;
                } else {
                    $category['deleted_at'] = $date;
                }
                unset($category['publish_flg']);

                if(isset($category['icon']) && $category['icon']!=''){
                    $imageInfo = explode('/', $category['icon']);
                    if(count($imageInfo)==2){
                        if ($imageInfo[0] == 'temp') {
                            $this->load->library('MyImage', 'myimage');
                            $this->myimage->move_upload('uploads/public/'.$this->image_folder.'/', TEMP_FOLDER_URL, CATEGORY_IMAGE_URL, $imageInfo[1], 'uploads/');
                        }
                        $category['icon'] = $imageInfo[1];
                    } else {
                        $category['icon'] = NULL;
                    }
                }
                $result = $this->cate_model->insert($category);
                if ($result) {
                    $aResult = array(
                        'code' => 1,
                        'text' => $this->lang->line('insert_success'),
                        'href' => admin_category_url($category['slug']));
                } else {
                    $aResult = array('code' => 0, 'title' => $this->lang->line('system_error'));
                }
            }
        }
        $this->renderJSON($aResult);
    }

    public function doUpdate() {
        $aResult = array();
        $category    = $this->input->post('category', true);
        $tCategory   = $this->input->post('category');
        $category_id = 0;
        if(!isset($tCategory['id'])){
            $aResult = array('code' => 1, 'text' => $this->lang->line('update_success'));
            $this->renderJSON($aResult);
            return;
        } else {
            unset($category['id']);
            $category_id = $this->encrypt->decode($tCategory['id']);
        }

        if (isset($category['title']) || isset($category['slug']) || isset($category['icon']) || isset($category['order'])) {
            $aResult = $this->fullUpdate($category_id, $category);
        } else {
            $aResult = $this->flashUpdate($category_id, $category);
        }
        $this->renderJSON($aResult);
    }

    private function flashUpdate($category_id, $category) {
        $aResult = array();
        $date = get_current_date();

        //set id
        if (isset($category['publish_flg']) && $category['publish_flg'] == 1) {
            $category['updated_at'] = $date;
            $category['deleted_at'] = null;
        } else {
            $category['deleted_at'] = $date;
        }
        unset($category['publish_flg']);

        $result = $this->cate_model->update($category_id, $category);
        if ($result) {
            $aResult = array('code' => 1, 'text' => $this->lang->line('update_success'));
        } else {
            $aResult = array('code' => 0, 'title' => $this->lang->line('system_error'));
        }
        return $aResult;
    }

    private function fullUpdate($category_id, $category) {
        $aResult = array();
        $date = get_current_date();
        $this->validate($category);
        if ($this->form_validation->run() == false) {
            $aResult = array(
                'code' => 0,
                'title' => $this->lang->line('insert_fail'),
                'text' => '<ul>' . validation_errors() . '</ul>',
                );
        } else {
            $postExist = $this->cate_model->checkCategoryExists($category['slug'], $category_id);
            if ($postExist > 0) {
                $aResult = array(
                    'code' => 0,
                    'title' => $this->lang->line('update_fail'),
                    'text' => '<ul><li>' . $this->lang->line('category_exist') . '</li></ul>',
                    );
            } else {
                if(isset($category['icon']) && $category['icon']!=''){
                    $imageInfo = explode('/', $category['icon']);
                    if(count($imageInfo)==2){
                        if ($imageInfo[0] == 'temp') {
                            $this->load->library('MyImage', 'myimage');
                            $this->myimage->move_upload('uploads/public/'.$this->image_folder.'/', TEMP_FOLDER_URL, CATEGORY_IMAGE_URL, $imageInfo[1], 'uploads/');
                        }
                        $category['icon'] = $imageInfo[1];
                    } else {
                        $category['icon'] = NULL;
                    }
                }

                if (isset($category['publish_flg']) && $category['publish_flg'] == 1) {
                    $category['updated_at'] = $date;
                    $category['deleted_at'] = null;
                } else {
                    $category['deleted_at'] = $date;
                }
                unset($category['publish_flg']);

                $result = $this->cate_model->update($category_id, $category);
                if ($result) {
                    $aResult = array(
                        'code'       => 1,
                        'text'       => $this->lang->line('update_success'),
                        'href'       => admin_category_url($category['slug']),
                        'front_href' => category_url($category['slug'])
                    );
                } else {
                    $aResult = array('code' => 0, 'title' => $this->lang->line('system_error'));
                }
            }
        }
        return $aResult;
    }
}
?>